import axios from "axios";
import store from "@/store";

import {Toast} from "vant";
import {getItem} from "@/utils/auth";


const token = localStorage.getItem('accessKey')
const language = localStorage.getItem('lang')

const api = axios.create({
    baseURL:process.env.VUE_APP_API_ROOT,
    withCredentials: false, //cookie 设置
    maxRedirects: 5,
    timeout: 8000,
})




// 请求拦截器
api.interceptors.request.use(
    config => {

        // 当前为请求超过拦截器
        if (token) {
            config.headers['like-admin']=token
        }else{
            config.headers['like-admin']= store.state.token
        }
        config.headers['lang-admin'] = getItem('lang') || 'en'
        return config
    },
    error => {
        return Promise.reject(error)
    })

// 处理一下响应的请求
api.interceptors.response.use(response => {
        const code = response.data.code
        switch (code){
            case 200:{
                return response.data
            }
            case 300:{
                return Promise.reject(response.data)
            }
            case 404:{

                return Promise.reject(response.data)
            }
            case 333:{

                // localStorage.removeItem('user')
                // localStorage.removeItem('accessKey')
                // sessionStorage.removeItem('detailId')
                // setTimeout(()=>{location.reload()},500)
                return Promise.reject(response.data)
            }
            case 500:{
                Toast(response.data.msg)
                return Promise.reject(response.data)
            }
            case 501:{
                Toast(response.data.msg)
                return Promise.reject(response.data)
            }
            case 405:{
                Toast(response.data.msg)
                return Promise.reject(response.data)
            }
            default:{
                Toast(response.data.msg)
                return Promise.reject(response.data)
            }
        }
    },
    error => {
        return Promise.reject(error)
    })


export  default api
